import { fileURLToPath, URL } from 'node:url';

import { defineConfig, loadEnv, ConfigEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import { VantResolver } from '@vant/auto-import-resolver';
import VueSetupExtend from 'vite-plugin-vue-setup-extend';

// https://vite.dev/config/
export default defineConfig(({ mode }): any => {
    // 获取自定义环境变量
    const env = loadEnv(mode, process.cwd());
    console.log(env.VITE_CONFIG_BASE_URL);

    console.log(`当前环境为：-----[${mode}]-----`);

    return {
        base: mode === 'production' ? '/Signatures_admin/' : '',
        plugins: [
            vue(),
            AutoImport({
                resolvers: [ElementPlusResolver(), VantResolver()],
            }),
            Components({
                resolvers: [ElementPlusResolver(), VantResolver()],
            }),
            VueSetupExtend(), // 添加插件
        ],
        build: {
            rollupOptions: {
                output: {
                    // 禁用保留模块结构（合并文件）
                    preserveModules: false,
                    // 自定义输出文件名格式
                    entryFileNames: 'assets/[name]-[hash].js',
                    chunkFileNames: 'assets/[name]-[hash].js',
                    assetFileNames: 'assets/[name]-[hash][extname]',
                },
            },
        },
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url)),
            },
            extensions: ['.js', '.ts', '.vue', '.json'], // 确保 .vue 扩展名被解析
        },
        css: {
            preprocessorOptions: {
                scss: {
                    silenceDeprecations: ['legacy-js-api'],
                },
            },
        },
        server: {
            host: '0.0.0.0',
            port: '3000',
            open: true,
            proxy: {
                '/api': {
                    target: env.VITE_BASE_URL,
                    changeOrigin: true,
                    // rewrite: (path: string) => path.replace(/^\/api/, ''),
                    configure: (proxy: any, options: any) => {
                        // 配置此项可在响应头中看到请求的真实地址
                        proxy.on('proxyRes', (proxyRes: any, req: any) => {
                            proxyRes.headers['x-real-url'] = new URL(req.url || '', options.target)?.href || '';
                        });
                    },
                },
                '/config': {
                    target: env.VITE_CONFIG_BASE_URL,
                    changeOrigin: true,
                    rewrite: (path: string) => path.replace(/^\/config/, ''),
                    configure: (proxy: any, options: any) => {
                        // 配置此项可在响应头中看到请求的真实地址
                        proxy.on('proxyRes', (proxyRes: any, req: any) => {
                            proxyRes.headers['x-real-url'] = new URL(req.url || '', options.target)?.href || '';
                        });
                    },
                },
            },
        },
    };
});
